import App from "../framework/App";
import CommonUtils from "../CommonUtils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Wait extends cc.Component {

    @property(cc.Node)
    bg: cc.Node = null;

    @property(cc.Node)
    icon: cc.Node = null;

    static instance: Wait = null;

    private destroyTimer = 0;
    private onAutoCloses: Function[] = [];

    /**
     * 显示全屏等待，禁止所有按键交互
     * @param timeout 默认5秒自动移除，0则不自动移除
     * @param onClose 删除时回调
     */
    static show(timeout = 5, onAutoClose?: Function) {
        if (!Wait.instance) {
            Wait.instance = cc.instantiate(App.instance.wait).getComponent(Wait);
            App.instance.node.addChild(Wait.instance.node);
        }
        Wait.instance.onAutoCloses.push(onAutoClose);
        Wait.instance.destroyTimer = timeout;
    }

    /** 隐藏全屏等待(主动移除不触发回调) */
    static hide() {
        if (Wait.instance) {
            Wait.instance.onAutoCloses = [];
            Wait.instance.node.destroy();
            Wait.instance = null;
        }
    }

    onDestroy() {
        this.onAutoCloses.forEach(onAutoClose => {
            onAutoClose && onAutoClose();
        });
        Wait.instance = null;
    }

    onLoad() {
        CommonUtils.setTouchMask(this.bg);
    }

    update(dt: number) {
        this.icon.angle += dt * 300;
        if (this.destroyTimer > 0) {
            this.destroyTimer -= dt;
            if (this.destroyTimer <= 0) {
                this.node.destroy();
            }
        }
    }

}
